const express = require("express");
const multer = require('multer');
const fs =require('fs');
const utils = require("../utils/index.js");
const router = express.Router();
const storage = multer.memoryStorage();
const OSS = require('ali-oss');
const ossClient = new OSS({
  region: 'oss-cn-hangzhou',
  accessKeyId: 'LTAI5t76WRMSS5pVauMDgDBz',
  accessKeySecret: '2Vh1t6SqEQql5o4GpAb8hg8DLzOn2e',
  bucket: 'sx-manage',
  secure:true,
});
const upload = multer({
  storage,
  limits: { fileSize: 5 * 1024 * 1024 }, // 5MB限制
  fileFilter: (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('仅允许上传图片文件!'));
    }
  }
});
router.post('/uploadOss', upload.array('file', 10), async (req, res) => {
  console.log(12,req.files);
  try {
    if (!req.files || req.files.length === 0) {
      res.send(utils.returnData({code: 200,data: []}));
    }else{
      // 上传所有文件到OSS
      const uploadPromises = req.files.map(file => {
        const filename =utils.getDataString()+'-'+ `${file.originalname}`;
        return ossClient.put(`images/${filename}`, file.buffer);
      });
      const results = await Promise.all(uploadPromises);
      const urls = results.map(result => result.url);
      res.send(utils.returnData({code: 200,data: urls}));
    }
  } catch (err) {
    console.error('上传失败:', err);
    return res.send(utils.returnData({code: -1,err,req}));
  }
});
module.exports = router;
